// 全局变量
let isDrawing = false;
let startX = 0;
let startY = 0;
let selectionBox = null;
let answerDisplayBox = null; // 新增：用于显示答案的 DIV 框
let isEnabled = false;

console.log('[Screenshot Extension] Content script loaded');

// 创建选择框元素
function createSelectionBox() {
  console.log('[Screenshot Extension] Creating selection box');
  const box = document.createElement('div');
  box.id = '#my-drag-selection-box';
  box.style.position = 'fixed';
  box.style.border = '2px dashed #4A90E2';
  box.style.backgroundColor = 'rgba(74, 144, 226, 0.2)';
  box.style.zIndex = '2147483647';
  box.style.pointerEvents = 'none';
  box.style.display = 'none';
  document.body.appendChild(box);
  console.log('[Screenshot Extension] Selection box created');
  return box;
}

// ----------------------------------------------------
// --- START: 答案显示框逻辑 ---
// ----------------------------------------------------

/**
 * 创建并初始化答案显示框
 * **高度为 250px，位置为居下显示**
 */
function createAnswerDisplayBox() {
  console.log('[Screenshot Extension] Creating answer display box');
  const box = document.createElement('div');
  box.id = 'answer-display-box';
  
  // CSS 样式设置，符合要求：800*250，半透明灰色
  box.style.position = 'fixed';
  box.style.width = '800px';
  box.style.height = '250px'; // **250px 高度**
  box.style.backgroundColor = 'rgba(50, 50, 50, 0.85)'; // 深灰色，半透明
  box.style.color = '#fff';
  box.style.border = '1px solid #333';
  box.style.borderRadius = '8px';
  box.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
  box.style.zIndex = '2147483647'; // 确保在最上层
  box.style.padding = '15px';
  box.style.overflowY = 'auto'; // 允许内容滚动
  box.style.fontFamily = 'Microsoft YaHei, sans-serif';
  
  // 居下居中计算
  box.style.top = 'auto'; 
  box.style.bottom = '20px'; // 底部留出 20px 边距
  box.style.left = '50%';
  box.style.transform = 'translateX(-50%)'; // 仅水平居中
  box.style.display = 'none'; // 默认隐藏
  
  document.body.appendChild(box);
  console.log('[Screenshot Extension] Answer display box created');
  return box;
}

/**
 * 构建并显示搜索结果内容
 * @param {string} keyword 搜索关键词
 * @param {Array<Object>} results 搜索结果数组
 * @param {string} error 错误信息
 */
function displayAnswerResults(keyword, results, error) {
    if (!answerDisplayBox) {
        answerDisplayBox = createAnswerDisplayBox();
    }
    
    // 清空现有内容
    answerDisplayBox.innerHTML = '';
    
    let contentHTML = '';
    
    // 辅助函数：替换 \n 为 <br> 并安全转义 HTML
    const formatText = (text) => {
        // 临时占位符，用于保护 <br> 标签不被后续的 HTML 转义操作所影响
        const PLACEHOLDER = '__BR_TEMP__';

        let htmlReadyText = text;
        
        // 1. 替换字面字符串 "\n" 和实际的换行符 "\n" 为占位符
        // 替换字面字符串 "\\n" (两个字符)
        htmlReadyText = htmlReadyText.replace(/\\n/g, PLACEHOLDER); 
        // 替换实际的换行符 "\n" (单个字符)
        htmlReadyText = htmlReadyText.replace(/\n/g, PLACEHOLDER);
        
        // 2. 转义基本的 HTML 字符，防止 XSS 和破坏格式
        htmlReadyText = htmlReadyText.replace(/&/g, '&amp;')
                                     .replace(/</g, '&lt;')
                                     .replace(/>/g, '&gt;')
                                     .replace(/"/g, '&quot;')
                                     .replace(/'/g, '&#39;');
                                     
        // 3. 将占位符还原为 HTML 换行标签 <br>
        htmlReadyText = htmlReadyText.replace(new RegExp(PLACEHOLDER, 'g'), '<br>');

        return htmlReadyText;
    };
    
    if (error) {
        // 显示错误信息
        contentHTML += `
            <div style="color: #FF6347; font-weight: bold; font-size: 1.1em;">❌ 题库搜索失败</div>
            <div style="margin-top: 10px; color: #ccc;">原因: ${error}</div>
        `;
    } else {
        // 显示关键词和匹配结果数量 (蓝色字体)
        contentHTML += `
            <div style="padding-bottom: 10px; border-bottom: 1px solid #666; margin-bottom: 10px;">
                <span style="color: #90BFFF; font-weight: bold;">搜索条件：</span>
                <span style="color: #4A90E2; font-weight: bold; font-size: 1.1em;">${formatText(keyword)}</span>
                <span style="float: right; color: #ccc;">匹配到 ${results.length} 条结果</span>
            </div>
        `;

        if (results.length > 0) {
            // 循环展示问题和答案
            results.forEach(item => {
                // 格式化问题和答案文本，处理换行 (\n -> <br>) 并去除首尾空格
                const formattedQuestion = formatText(item.question).trim();
                const formattedAnswer = formatText(item.answer).trim();
                
                contentHTML += `
                    <div style="margin-bottom: 15px; border-bottom: 1px dotted #444; padding-bottom: 5px; line-height: 1.5;">
                        <div style="color: #A9F5A9; font-weight: bold;">
                            ${formattedQuestion}
                        </div>
                        <div style="color: #FF6347; margin-left: 20px; font-weight: bold;">
                            正确答案：${formattedAnswer}
                        </div>
                    </div>
                `;
            });
        } else {
             contentHTML += `<div style="color: #FFC107;">未在题库中搜索到匹配结果。</div>`;
        }
    }
    
    answerDisplayBox.innerHTML = contentHTML;
    answerDisplayBox.style.display = 'block';
    
    // 监听点击事件，点击框体后隐藏
    answerDisplayBox.onclick = () => {
        answerDisplayBox.style.display = 'none';
        answerDisplayBox.onclick = null; // 移除事件监听器
    };
    
    console.log('[Screenshot Extension] Answer results displayed.');
}

// ----------------------------------------------------
// --- END: 答案显示框逻辑 ---
// ----------------------------------------------------


// 鼠标按下事件
function handleMouseDown(e) {
  console.log('[Screenshot Extension] Mouse down event:', {
    isEnabled,
    button: e.button,
    clientX: e.clientX,
    clientY: e.clientY
  });
  
  if (!isEnabled || e.button !== 0) {
    console.log('[Screenshot Extension] Mouse down ignored - isEnabled:', isEnabled, 'button:', e.button);
    return;
  }
  
  // 隐藏答案框（如果可见）
  if (answerDisplayBox) {
      answerDisplayBox.style.display = 'none';
  }

  isDrawing = true;
  startX = e.clientX;
  startY = e.clientY;
  
  console.log('[Screenshot Extension] Starting drawing at:', startX, startY);
  
  if (!selectionBox) {
    selectionBox = createSelectionBox();
  }
  
  selectionBox.style.left = startX + 'px';
  selectionBox.style.top = startY + 'px';
  selectionBox.style.width = '0px';
  selectionBox.style.height = '0px';
  selectionBox.style.display = 'block';
  
  e.preventDefault();
}

// 鼠标移动事件
function handleMouseMove(e) {
  if (!isDrawing || !isEnabled) return;
  
  const currentX = e.clientX;
  const currentY = e.clientY;
  
  const width = Math.abs(currentX - startX);
  const height = Math.abs(currentY - startY);
  const left = Math.min(startX, currentX);
  const top = Math.min(startY, currentY);
  
  selectionBox.style.left = left + 'px';
  selectionBox.style.top = top + 'px';
  selectionBox.style.width = width + 'px';
  selectionBox.style.height = height + 'px';
}

// 鼠标释放事件
async function handleMouseUp(e) {
  console.log('[Screenshot Extension] Mouse up event:', {
    isDrawing,
    isEnabled,
    clientX: e.clientX,
    clientY: e.clientY
  });
  
  if (!isDrawing || !isEnabled) {
    console.log('[Screenshot Extension] Mouse up ignored');
    return;
  }
  
  isDrawing = false;
  
  const endX = e.clientX;
  const endY = e.clientY;
  
  const x = Math.min(startX, endX);
  const y = Math.min(startY, endY);
  const width = Math.abs(endX - startX);
  const height = Math.abs(endY - startY);
  
  console.log('[Screenshot Extension] Selection area:', { x, y, width, height });
  
  // 隐藏选择框
  if (selectionBox) {
    selectionBox.style.display = 'none';
  }
  
  // 如果选择区域太小，不进行截图
  if (width < 10 || height < 10) {
    console.log('[Screenshot Extension] Area too small, skipping screenshot');
    return;
  }
  
  // 截图
  console.log('[Screenshot Extension] Starting screenshot...');
  await captureScreenshot(x, y, width, height);
}

// 截图函数
async function captureScreenshot(x, y, width, height) {
  try {
    console.log('[Screenshot Extension] captureScreenshot called with:', { x, y, width, height });
    
    // 获取设备像素比
    const dpr = window.devicePixelRatio || 1;
    console.log('[Screenshot Extension] Device pixel ratio:', dpr);
    
    const area = {
      x: x * dpr,
      y: y * dpr,
      width: width * dpr,
      height: height * dpr
    };
    
    console.log('[Screenshot Extension] Adjusted area for DPR:', area);
    
    // 发送消息给 background script 进行截图
    console.log('[Screenshot Extension] Sending message to background script...');
    chrome.runtime.sendMessage({
      action: 'captureScreenshot',
      area: area
    }, (response) => {
      console.log('[Screenshot Extension] Response from background:', response);
      if (chrome.runtime.lastError) {
        console.error('[Screenshot Extension] Chrome runtime error:', chrome.runtime.lastError);
      }
    });
    
  } catch (error) {
    console.error('[Screenshot Extension] Screenshot error:', error);
  }
}

// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('[Screenshot Extension] Message received from background:', request);
  
  if (request.action === 'toggleScreenshot') {
    isEnabled = request.enabled;
    console.log('[Screenshot Extension] Screenshot mode:', isEnabled ? 'ENABLED' : 'DISABLED');
    
    if (isEnabled) {
      console.log('[Screenshot Extension] Adding event listeners');
      document.addEventListener('mousedown', handleMouseDown, true);
      document.addEventListener('mousemove', handleMouseMove, true);
      document.addEventListener('mouseup', handleMouseUp, true);
    } else {
      console.log('[Screenshot Extension] Removing event listeners');
      document.removeEventListener('mousedown', handleMouseDown, true);
      document.removeEventListener('mousemove', handleMouseMove, true);
      document.removeEventListener('mouseup', handleMouseUp, true);
      
      if (selectionBox) {
        selectionBox.style.display = 'none';
      }
      // 禁用时隐藏答案框
      if (answerDisplayBox) {
          answerDisplayBox.style.display = 'none';
      }
    }
    
    sendResponse({ success: true });
  } else if (request.action === 'displayAnswers') {
    // 处理来自 background script 的答案显示请求
    console.log('[Screenshot Extension] Received answers for display:', request.results.length);
    displayAnswerResults(request.keyword, request.results, request.error);
    sendResponse({ success: true, message: 'Answer box displayed' });
  }
  
  return true;
});